package com.smartgame.controllers;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.utils.Pool;
import com.smartgame.objects.Background;
import com.smartgame.objects.Cobweb;
import com.smartgame.objects.Spiders;
import com.smartgame.screens.MenuScreen;
import com.smartgame.util.Assets;
import com.smartgame.util.GdxUtil;

public class GameController extends AbstractController {

	public static final String TAG = GameController.class.getName();
	
	// No necessary to use pool because our logic is simple and has only few
	// objects. implement it here for demo and future use.
	private Pool<Spiders> spidersPool = new Pool<Spiders>() {
		@Override
		protected Spiders newObject() {
			return new Spiders(Assets.instance.spiders.animatedTexture);
		}
	};
	private Pool<Background> backgroundPool = new Pool<Background>() {
		@Override
		protected Background newObject() {
			return new Background();
		}
	};
	private Pool<Cobweb> cobwebPool = new Pool<Cobweb>() {
		@Override
		protected Cobweb newObject() {
			// test code
			return new Cobweb(Assets.instance.spiders.animatedTexture);
		}
	};

	// objects for renderer
	private Spiders spiders;
	private Background background;

	public GameController(Game game) {
		super(game);

		// invoke free() to free object to the pool if no longer use it.
		spiders = spidersPool.obtain(); 
		background = backgroundPool.obtain();
		rendererList.add(background);
		rendererList.add(spiders);

		cameraHelper.setTarget(spiders);
	}

	@Override
	public void update(float deltaTime) {
		super.update(deltaTime);

		// my own update goes here!
		// spiders enters into center of the second background
		float viewWidth = GdxUtil.getViewPortWidth();
		if ((spiders.position.x + spiders.origin.x) >= viewWidth) {
			// reset the spiders to center of the first background
			spiders.position.x -= viewWidth;
			cameraHelper.update(deltaTime);
		}
	}
	
	@Override
	public boolean touchDown(int x, int y, int pointer, int button) {
		// testing code
		float posDiff = ((float) x / Gdx.graphics.getWidth() - 0.5f) * GdxUtil.getViewPortWidth();
		spiders.position.x += posDiff;
		
		Cobweb cobweb = cobwebPool.obtain();
		cobweb.position.x = x;
		cobweb.position.y = y;
		rendererList.add(cobweb);
		return true;
	}
	
	@Override
	public boolean keyDown(int keycode) {
		if (keycode == Keys.BACK) {
			// Optional back button handling (e.g. ask for confirmation)
			game.setScreen(new MenuScreen(game));
		}
		return false;
	}

}
